#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);
use SIM_base;
use SIM_settings;
use SIM_cgi;
use SIM_trafficInfo;
use SIM_nodeInfo;

#BEGIN { $Exporter::Verbose=1 }

# Startupscript translater

my $tool = $ARGV[0];
my $action = $ARGV[1];
my $firewall = $ARGV[2];
my $option1 = $ARGV[3];

if ( "$action" eq "" ) {
  $action = "none";
}


my $backHeader="black";
my $printVerbose="notquiet";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $dloadDir = $ENV{'SIM_DLOADSTMPDIR'};
my $domainDir = $ENV{'SIM_DOMAINDIR'};
my $baseDir = "$domainDir/fw-database";
my $confDir = "$baseDir/configs";
my $currDevConfDir = "$domainDir/device-configs/current";
my $dbaseDir = "$baseDir/dbase";
my $unmatchedTrafDir = "$dbaseDir/unmatchedTraf";
my $oldDbDir = "$baseDir/dbaseOld";
my $infoDir = "$dbaseDir/info";
my $fwDir = "$dbaseDir/fws";
my $hostDir = "$dbaseDir/hosts";
my $ipDir = "$dbaseDir/ips";
my $interfaceDir = "$dbaseDir/interfaces";
my $objectDir = "$dbaseDir/objects";
my $serviceDir = "$objectDir/service";
my $aclDir = "$dbaseDir/acls";
my $accessGroupDir = "$dbaseDir/access-group";
my $ruleDir = "$dbaseDir/rules";
my $tunixNatDir = "$dbaseDir/tunixNat";
my $pixNatDir = "$dbaseDir/pixNat";
my $tmpDir = "$dbaseDir/tmp";
my $tmpNatDir = "$dbaseDir/tmp/nat";

sub catFile {
  my $output = "";
  my ($file) = @_;
  open FH, $file or $output = "none";
# $output = readline FH;
  $output = <FH>;
  close FH;
  return $output;
}

sub catFileLine {
  my $outPut = "";
  my ($file) = @_;
  open FH, $file or $outPut = "$file";
  $outPut = <FH>;
  close FH;
  chomp($outPut);  # remove the newline
  return $outPut;
}

sub testParam {
  my $file = "@_[0]";
  my $parameter = "@_[1]";
  my $update = "@_[2]";
  my $result = param("$parameter");
  if ( "$result" eq "" ) {
#   print("cat ");
    $result = &catFileLine("$file");
  } else {
    if ( "$update" eq "upd" ) { 
      printFileLine("$file","$parameter","$result","$printVerbose");
    }
  }
# print("$result $file<BR>");
  return("$result");
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  #print ("testname=$testname");
  return $testname;
}

sub expandIp {
  my $ipAddr = "@_[0]";
  my @pieces = split('\.', $ipAddr);
  my $returnIp;

  foreach my $chunk (@pieces) {
    my $eChunk = sprintf("%03d", $chunk);
    if ( "$returnIp" eq "" ) {
      $returnIp = "$eChunk";
    } else {
      $returnIp = "$returnIp.$eChunk";
    }
  }
  return $returnIp;
}
 
sub printFirewalls {
  if ( -d $fwDir ) {
    #chdir($fwDir);
    #my $fwList = catFileLine("$confDir/firewall-list");
    #my @firewalls = split(/ /, $fwList);
    chdir($fwDir);
    my @firewalls = <*>;
    foreach my $instance (@firewalls) {
      my $fontColor;
      if ( "$instance" eq "$firewall" ) {
        $fontColor = "red";
      } else {
        $fontColor = "#333333";
      }
      my $urlAction = $action;
      if ( "$action" eq "analyse" ) {
        $urlAction = "none";
      }
      print(". <A HREF=$httpScriptName?fwan+$urlAction+$instance+$option1><FONT COLOR=$fontColor>$instance</FONT></A> .");
    }
    print("</TD></TR><TR BGCOLOR=#EEEEEE><TD COLSPAN=10><CENTER>");
  }
}

sub printMainMenu {
  print("<FONT COLOR=#666666>");
  printMenu("fwan","line", $tool, $action, $firewall, $option1);
  print("</FONT></TD></TR></TABLE><CENTER>");
}

sub splitObject {
  my $objectName = "@_[0]";
  my ( $returnObject, $dummy ) = split('_ref', $objectName);
  return($returnObject);
}

sub runAnalyse {
  print("Analysing config files in $currDevConfDir. <BR>");
  if ( !-d "$currDevConfDir" ) {
    print("Oops, no device config dir found. ($currDevConfDir)");
  } elsif ( !-d $confDir ) {
    print ("Oops, no confDir found, please configure your firewalls under the <B>list</B> option.");
  } else {
    print ("Rebuilding firewall database...<BR>");
    my $extInfoFile = "$SIMparam{'SIMfixedInfoDir'}/fwrbHosts.txt";
    if ( -f $extInfoFile ) {
      unlink( $extInfoFile );
    }
    printFileLine($extInfoFile, "header", "# Config file generated by the FW-Analyser, will automatically be replaced.\n");
    if (( -d "$dbaseDir" ) and ( "$dbaseDir" ne "" )) {
      if ( -d $oldDbDir ) {
        print("Found old dir, moved it to speed up things ($oldDbDir ==&gt; $dbaseDir.<BR>");
        system("mv $oldDbDir $dbaseDir");
      }
      system("mv $dbaseDir $oldDbDir");
    } else {
      print("No old data found in $dbaseDir.<BR>");
    }
    # timestamp zetten om versie database te laten zien.
    my $timeStamp = time;
    testMkDir($infoDir);
    printFileLine("$infoDir/lastAnalyse","Reanalised","$timeStamp","$printVerbose");
    chdir $confDir;
    my $fwList = catFileLine("$confDir/firewall-list");
    my @fwArray;
    if ( "$fwList" eq "all" ) {
      chdir($currDevConfDir);
      @fwArray = <*>;
      printf("<B>Searching all firewall configs</B>.<BR>");
    } else {
      printf("<B>Using firewall configlist \"$fwList\"</B>.<BR>");
      @fwArray = split(/ /, $fwList);
    }
    foreach my $firewall (@fwArray) {
      if ( -f "$currDevConfDir/$firewall") {
        print("<BR><B>Analysing $firewall</B>");
        open (CONFIG, "$currDevConfDir/$firewall");
        while (my $regel = <CONFIG>) {
          my @word = split(' ', "$regel");
          if (( "$word[0]" eq "FWSM" ) and ( "$word[1]" eq "Version" )) {
            print(", this is an Cisco Fwsm.<BR>");
            close(CONFIG);
            &analyseFwsm("$currDevConfDir/$firewall", $extInfoFile);
            printFileLine("$infoDir/lastAnalyse-$firewall","Reanalised $firewall","$timeStamp","$printVerbose");
            last;
          } elsif (( "$word[0]" eq "ASA" ) and ( "$word[1]" eq "Version" )) {
            print(", this is an Cisco ASA.<BR>");
            close(CONFIG);
            &analyseFwsm("$currDevConfDir/$firewall", $extInfoFile);
            printFileLine("$infoDir/lastAnalyse-$firewall","Reanalised $firewall","$timeStamp","$printVerbose");
            last;
          } elsif (( "$word[0]" eq "PIX" ) and ( "$word[1]" eq "Version" )) {
	    print(", this is an Cisco PIX.<BR>");
	    close(CONFIG);
	    &analyseFwsm("$currDevConfDir/$firewall", $extInfoFile);
            printFileLine("$infoDir/lastAnalyse-$firewall","Reanalised $firewall","$timeStamp","$printVerbose");
	    last;
          } elsif (( "$word[0]" eq "FW_HOSTNAME" ) and ( "$word[1]" eq "$firewall" )) {
            print(", this is an Tunix firewall.<BR>");
            close(CONFIG);
            &analyseTunix("$currDevConfDir/$firewall");
            printFileLine("$infoDir/lastAnalyse-$firewall","Reanalised $firewall","$timeStamp","$printVerbose");
            last;
          }
        }
        close(CONFIG);
      } else {
        print("Config for $firewall not found.<BR>");
      }
    }
  }
  if (( -d "$oldDbDir" ) and ( "$oldDbDir" ne "" )) {
    print("Removing old stuff in $oldDbDir, this may take a while, depending on your filesystem....<BR>");
    chdir($oldDbDir);
    my @dirList = <*>;
    foreach my $dirEntry (@dirList) {
      print(" $dirEntry ");
      system "rm -fR $oldDbDir/$dirEntry";
    }
    print("<PRE>");
    system("ls -la $oldDbDir");
    system("rmdir $oldDbDir");
    print("</PRE>");
  }
}

sub analyseTunix {
  my $firewall = "@_[0]";
  open (CONFIG, "$firewall");
  my ( $regel, $objectName, $systemName );
  while ($regel = <CONFIG>) {
    my @word = split(' ', "$regel");
    if ( "$word[0]" eq "FW_HOSTNAME" ) {
      $systemName = $word[1];
      chomp($systemName);
      testNameStrict($systemName);
      testMkDir("$fwDir");
      printFileLine("$fwDir/$systemName","systemname","$systemName","$printVerbose");
      print("Systemname $systemName.<P>");
    }
  }
  close(CONFIG);
  if ( "$systemName" ne "" ) {
    open (CONFIG, "$firewall");
    my ( $regel, $objectName );
    my $ruleNum = 0;
    my ( $fwClType, $d1, $d2, $d3, $fwClATypes, @fwClients );
    while ($regel = <CONFIG>) {
      my @word = split(' ', "$regel");
      if ( "$word[0]" eq "service" ) {
        # service pweb64          (T80 T443)=connect -dst 10.77.64.42 -src 0.0.0.0
        my $serviceName = $word[1];
        shift @word;
        shift @word;
        my ( $natDest, $natSource, $protocols, $action );
        my $next = "prot"; 
        foreach my $param (@word) {
          if ( "$next" eq "prot" ) {
            my ( $protPart, $conType ) = split(/=/, $param);
            if ( "$conType" ne "" ) {
              $action = "$conType";
              $next = "";
            }
            $protocols = "$protocols $protPart"
          } elsif ( "$param" eq "\-dst" ) {
            $next = "dst";
          } elsif ( "$next" eq "dst" ) {
            $natDest = $param;
            $next = "";
          } elsif ( "$param" eq "\-src" ) {
            $next = "src";
          } elsif ( "$next" eq "src" ) {
            $natSource = $param;
            $next = "";
          }
          #print("($param) n:$next,");
        }
        if ( "$natDest" ne "" ) {
          my $workDir = "$tmpNatDir/$serviceName";
          testMkDir($workDir);
           printFileLine("$workDir/$systemName-service","service","$systemName $serviceName","$printVerbose");
           printFileLine("$workDir/$systemName-natSource","natSource","$natSource","$printVerbose");
           printFileLine("$workDir/$systemName-natDest","natDest","$natDest","$printVerbose");
           printFileLine("$workDir/$systemName-protocols","protocols","$protocols","$printVerbose");
           printFileLine("$workDir/$systemName-action","action","$action","$printVerbose");
        }
        #print("serviceName=$serviceName, 
        #       natDest=$natDest, natSource=$natSource, protocols=$protocols, action=$action.<BR>");
      } elsif ( "$word[0]" eq "rule" ) {
        # rule    everybody       193.173.83.64   pweb64 true     WEBACCES 64
        my $trafSource = $word[1];
        my $trafDest = $word[2];
        my $serviceName = $word[3];
        my $action = $word[4];
        shift @word; shift @word; shift @word; shift @word; shift @word;
        my $comment = join(' ', @word);
        my $workDir = "$tmpNatDir/$serviceName";
        if ( -d $workDir ) {
         printFileLine("$workDir/$systemName-trafSource","trafSource","$trafSource","$printVerbose");
         printFileLine("$workDir/$systemName-trafDest","trafDest","$trafDest","$printVerbose");
         printFileLine("$workDir/$systemName-comment","comment","$comment","$printVerbose");
        }
      } elsif (( "$word[0]" eq "pass" ) or ( "$word[0]" eq "xpass" ) or ( "$word[0]" eq "block" )) {
        $ruleNum++;
        #pass in log first quick on fxp0 proto tcp from 10.77.5.148/30 to 10.77.64.159/32 port eq 80 keep state group 2005
        my $action = $word[0];
        shift @word;
        my ( $direction, $flags, $interface, $protocol, $source, $destination, $protIn, $service );
        my $status = "init";
        foreach my $item (@word) {
          if (( "$item" eq "in" ) or ( "$item" eq "out" )) {
            $direction = $item;
          } elsif ( "$item" eq "proto" ) {
            $status = "proto";
          } elsif ( "$item" eq "from" ) {
            $status = "from";
          } elsif ( "$item" eq "to" ) {
            $status = "to";
          } elsif ( "$item" eq "on" ) {
              $status = "on";
          } elsif ( "$status" eq "init" ) {
            if ( "$item" ne "on" ) {
              $flags = "$flags $item";
            } else {
              $status = "on";
            }
          } elsif ( "$status" eq "on" ) {
            $interface = $item;
            $status = "";
          } elsif ( "$status" eq "proto" ) {
            $protocol = $item;
            $status = "";
          } elsif ( "$status" eq "from" ) {
            $source = $item;
            $status = "protin";
          } elsif ( "$status" eq "protin" ) {
            if ( "$item" eq "to" ) {
              $status = "to";
            } else {
              $protIn = "$protIn $item";
            }
          } elsif ( "$status" eq "to" ) {
            $destination  = $item;
            $status = "service";
          } elsif ( "$status" eq "service" ) {
            if (( "$item" ne "flags" ) and ( "$item" ne "keep" ) and ( "$item" ne "group" ) and ( "$item" ne "hash" )) { 
              #print("s:$item ");
              $service = "$service $item";
            } else {
              $flags = "$flags $item";
              $status = "flags";
            }
          } else {
            $flags = "$flags $item";
          }
        }
        print(" . ");
        #reccord wegschrijven.
        my $dispNum = sprintf("%04d", $ruleNum);
        my $workDir = "$ruleDir/rule-$systemName-=-$dispNum";
        testMkDir("$workDir");
        printFileLine("$workDir/interface","Interface","$interface","$printVerbose");
        printFileLine("$workDir/direction","Direction","$direction","$printVerbose");
        printFileLine("$workDir/action","action","$action","$printVerbose");
        printFileLine("$workDir/protocol","protocol","$protocol","$printVerbose");
        printFileLine("$workDir/flags","flags","$flags","$printVerbose");
        splitIp("in","$source","$workDir","$dispNum","$systemName");
        splitIp("out","$destination","$workDir","$dispNum","$systemName");
        printFileLine("$workDir/service-in","service-out","$protIn","$printVerbose");
        printFileLine("$workDir/service-out","service-out","$service","$printVerbose");
        #FW_CLTYPE_P_WWW201      Phttp201 Phttps201
        #FW_CLIENTS_P_WWW201     internet ....
        #FW_SERVERS_P_WWW201     193.173.145.201
        #shift @word;
        #fwClType, $d1, $d2, $d3, @fwClATypes, @fwClients
        #my @array = ();
      } elsif ( substr($word[0], 0, 9) eq "FW_CLTYPE" ) {
        ( $d1, $d2, $d3, $fwClType ) = split(/_/, $word[0]);
        shift @word;
        $fwClATypes = join(' ', @word);
      } elsif ( substr($word[0], 0, 10) eq "FW_CLIENTS" ) {
        my ( $d1, $d2, $d3, $fwTest ) = split(/_/, $word[0]);
        #print(" $fwTest, $fwClType. ");
        if ( "$fwTest" eq "$fwClType" ) {
          shift @word;
          @fwClients = @word;
        }
      } elsif ( substr($word[0], 0, 10) eq "FW_SERVERS" ) {
        my ( $d1, $d2, $d3, $fwTest ) = split(/_/, $word[0]);
        if ( "$fwTest" eq "$fwClType" ) {
          my @testArray = split(/ /, $fwClATypes);
          foreach my $entry (@testArray) {
            print("entry: $entry ");
            #my $servName = substr($entry, 1);
            my $servName = $entry;
            my $workDir = "$tmpNatDir/$servName";
            testMkDir($workDir);
            my $trafDest = $word[1];
            my $trafSource = join(' ', @fwClients);
            print("trafentry from $trafSource to $trafDest in $workDir.<BR>");
            printFileLine("$workDir/$systemName-trafDest","trafDest","$trafDest","$printVerbose");
            printFileLine("$workDir/$systemName-trafSource","trafSource","$trafSource","$printVerbose");
          }
          @fwClients = ();
          $fwClATypes = "";
        }
      #} else {
      #  print(" substr($word[0], 0, 10). "); 
      }
    }
    if ( -d $tmpNatDir ) {
      my @dirList = <$tmpNatDir/*>;
      #$tunixNatDir expandIp
      foreach my $dirEntry (@dirList) {
        my @natEntries = <$dirEntry/*-service>;
        foreach my $netEntry (@natEntries) {
          my $servEntry = catFileLine("$netEntry"); 
          my ( $fwName, $service ) = split(/ /, $servEntry);
          if ( -f "$dirEntry/$fwName-trafDest" ) {
            my $dIpAddr = catFileLine("$dirEntry/$fwName-trafDest");
            my $EIpAddr = expandIp("$dIpAddr");
            print("Moving info for $service to $EIpAddr<BR>\n");
            my $destDir = "$tunixNatDir/$EIpAddr-$service";
            testMkDir($destDir);
            system("mv $dirEntry/$fwName-* $destDir");
          }
        } 
      }
    }
  }
}

sub testIpAddr {
  my $ipAddr = "@_[0]";
  my @ipArr = split('\.', $ipAddr);
  my $result = "";
  foreach my $entry (@ipArr) {
    if (( $entry ge 0 ) and ( $entry < 256 )) {
      $result = "$result x";
    } else {
      $result = "$result y";
    }
  }
  if ( "$result" eq " x x x x" ) {
    return 1;
  }
}

sub translateCiscoProts {
  # the folowing protocol types are hard coded in the cisco fw's.
  # rsh = tcp 514
  # syslog = udp 514
  my $prot = "@_[0]";
  my %protName = ( "ldap", 389, 
                   "ldaps", 636,
                   "sunrpc", 111, 
                   "syslog", 514, 
                   "rsh", 514, 
                   "smtp", 25, 
                   "ftp-data", 20, 
                   "ftp", 21, 
                   "ssh", 22, 
                   "https", 443, 
                   "www", 80, 
                   "domain", 53,
                   "lotusnotes", 1352 );
  if ( $protName{$prot} ne "" ) {
    $prot = $protName{$prot};
  }
  return $prot;
}

sub splitIp {
  my $direction = "@_[0]";
  my $entry = "@_[1]";
  my $workDir = "@_[2]";
  my $dispNum = "@_[3]";
  my $systemName = "@_[4]";
  my ( $ipAddr, $mask ) = split('/', $entry);
  my ( $type );
  if (( "$mask" eq "32" ) or ( "$mask" eq "" )) {
    $type = "ip";
  } else {
    $type = "subnet";
  }
  my @dotMask;
  $dotMask[8] = "255.0.0.0";
  $dotMask[16] = "255.255.0.0";
  $dotMask[24] = "255.255.255.0";
  $dotMask[25] = "255.255.255.128";
  $dotMask[26] = "255.255.255.192";
  $dotMask[27] = "255.255.255.224";
  $dotMask[28] = "255.255.255.240";
  $dotMask[29] = "255.255.255.248";
  $dotMask[30] = "255.255.255.252";
  $dotMask[32] = "";
  my $eIP = expandIp($ipAddr);
  my $testDir = "$ipDir/$eIP";
  testMkDir("$testDir");
  printFileLine("$testDir/firewall-$systemName","firewall","$systemName","$printVerbose");
  printFileLine("$testDir/ipaddr","ipAddress","$ipAddr","$printVerbose");
  printFileLine("$workDir/traffic-$direction","traffic-$direction","$type $ipAddr $dotMask[$mask]","$printVerbose");
  system "ln -s $workDir $testDir/rule-$systemName-=-$dispNum";
}

sub analyseFwsm {
  my $firewall = "@_[0]";
  my $extInfoFile = "@_[1]";
  my $systemName = "undefined";
  # First pass, to get some basic info needed later.
  open (CONFIG, "$firewall");
  my ( $regel);
  while ($regel = <CONFIG>) {
    my @word = split(' ', "$regel");
    if ( "$word[0]" eq "hostname" ) {
      $systemName = $word[1];
      chomp($systemName);
      testNameStrict($systemName);
      testMkDir("$fwDir");
      printFileLine("$fwDir/$systemName","systemname","$systemName","$printVerbose");
      print("Systemname $systemName.<P>");
    } elsif ( "$word[0]" eq "access-group" ) {
      my $aclName = $word[1];
      my $direction = $word[2];
      my $what = $word[3];
      my $intName = $word[4];
      testMkDir("$accessGroupDir");
      printFileLine("$accessGroupDir/$systemName-$aclName","aclInfo","$aclName $direction $what $intName","$printVerbose");
    }
  }
  close(CONFIG);
  # tweede keer, rest van de gegevens ophalen.
  open (CONFIG, "$firewall");
  my $ruleNum = 1;
  my $remarkNum = 1;
  my ( $regel, $objectType, $objectName, $workDir );
  while ($regel = <CONFIG>) {
    chomp($regel);
    print("<PRE>$regel</PRE>");
    my @word = split(' ', "$regel");
    if ( "$word[0]" eq "!" ) {
      # reset variables if an empty line is found (usualy between sections.
      $objectType = "";
    } elsif ( "$word[0]" eq "name" ) {
      my $ipAddress = $word[1];
      my $hostName = $word[2];
      testNameStrict($hostName);
      my $hostDir = "$hostDir/$hostName";
      testMkDir("$hostDir");
      printFileLine("$hostDir/ipaddr-$systemName-$ipAddress","ipAddress","$systemName $ipAddress","$printVerbose");
      my $eIP = expandIp($ipAddress);
      my $workDir = "$ipDir/$eIP";
      testMkDir("$workDir");
      printFileLine("$workDir/firewall-$systemName","firewall","$systemName","$printVerbose");
      printFileLine("$workDir/hostname-$systemName-=-$hostName","hostname","$hostName","$printVerbose");
      printFileLine("$workDir/ipaddr","ipAddress","$ipAddress","$printVerbose");
      printFileLine($extInfoFile, "append", "$systemName $ipAddress $hostName");
      my $description = "";
      if ( "$word[3]" eq "description" ) {
        shift @word; shift @word; shift @word; shift @word;
	$description = join(' ', @word);
        &testMkDir("$hostDir");
	printFileLine("$hostDir/description-$systemName","description","$description","$printVerbose");
        printFileLine($extInfoFile, "append", ", $description");
      }
      printFileLine($extInfoFile, "append", "\n");
    } elsif ( "$word[0]" eq "interface" ) {
       my $intName = $word[1];
       $workDir = "$interfaceDir/$intName";
       testMkDir("$workDir");
       $objectType = "interface";
    } elsif ( "$word[0]" eq "nameif" ) {
      #nameif Public_Presentation 
      my $nameIf = $word[1];
      printFileLine("$workDir/nameIf-$systemName","nameIf","$nameIf","$printVerbose");
    } elsif ( "$word[0]" eq "security-level" ) {
      my $securityLevel = $word[1];
      printFileLine("$workDir/securityLevel-$systemName","securityLevel","$securityLevel","$printVerbose");
    } elsif (( "$word[0]" eq "ip" ) and ( "$word[1]" eq "address" )) {
      my $ipAddr = $word[2];
      my $netmask = $word[3];
      my $standby = $word[4];
      my $ipStandby = $word[5];
      printFileLine("$workDir/ipaddr-$systemName-$ipAddr","ipAddress","$systemName $ipAddr $netmask","$printVerbose");
      if ( "$standby" eq "standby" ) {
        printFileLine("$workDir/standby-$systemName","standby Ip","$ipStandby","$printVerbose");
      }
    } elsif (( "$word[0]" eq "object-group" ) or ( "$word[0]" eq "object" )) {
      # object-group network DL01AS84
      # object-group service WEB tcp
      $objectType = $word[1];
      if ( "$objectType" eq "icmp-type" ) {
        #object-group icmp-type DM_INLINE_ICMP_1
        $objectType = "service";
      }
      $objectName = $word[2];
      $objectName = splitObject($objectName);
      my $objectProt = $word[3];
      $workDir = "$objectDir/$objectType/$systemName-=-$objectName";
      testMkDir("$workDir");
      printFileLine("$workDir/object-type-$systemName","object-type","$systemName $objectType","$printVerbose");
      printFileLine("$workDir/object-name","object-name","$objectName","$printVerbose");
      if ( "$objectProt" ne "" ) {
        printFileLine("$workDir/object-protocol-$systemName","object-protocol","$objectProt","$printVerbose");
      }
    } elsif ( "$word[0]" eq "description" ) {
      shift @word;
      my $description = join(' ', @word);
      if (( "$objectType" ne "interface" ) and ( "$objectType" ne "" )) {
        $workDir = "$objectDir/$objectType/$systemName-=-$objectName";
      }
      testMkDir($workDir);
      printFileLine("$workDir/description-$systemName","descryption","$description","$printVerbose");
    } elsif ( "$word[0]" eq "service-object" ) {
      shift @word;
      if ( "$word[0] $word[1]" eq "port eq") {
        $word[2] = translateCiscoProts($word[2]);
      }
      my $service = join('_', @word);
      printFileLine("$workDir/service-$systemName-$service","service","$systemName service_$service","$printVerbose");
    } elsif ( "$word[0]" eq "icmp-object" ) {
      shift @word;
      my $service = join('_', @word);
      printFileLine("$workDir/service-$systemName-$service","icmp","$systemName icmp_$service","$printVerbose");
    } elsif ( "$word[0]" eq "port-object" ) {
      shift @word;
      if ( "$word[0]" eq "eq" ) {
        $word[1] = translateCiscoProts($word[1]);
      }
      my $service = join('_', @word);
#     printFileLine("$workDir/service-$systemName-$service","service","$systemName port-object $service","$printVerbose");
      printFileLine("$workDir/service-$systemName-$service","service","$systemName port_$service","$printVerbose");
    } elsif (( "$word[0]" eq "network-object" ) or ((( "$word[0]" eq "subnet" ) or ( "$word[0]" eq "host" )) and ( $objectType eq "network" ))) {
      # host INET_nodns3
      # Internal_Hosts 255.0.0.0
      my ( $hostname, $netmask );
      if ( "$word[0]" eq "subnet" ) {
        $objectType = "subnet";
        $hostname = $word[1];
        $netmask = $word[2];
      } elsif ( "$word[0]" eq "host" ) {
        $objectType = "subnet";
        $hostname = $word[1];
        if ( !-d "$hostDir/$hostname" ) {
          $objectType = "ip";
        }
      } elsif ( "$word[1]" eq "host" ) {
        $objectType = "host";
        $hostname = $word[2];
        if ( !-d "$hostDir/$hostname" ) {
          $objectType = "ip";
        }
      } elsif ( "$word[1]" eq "object" ) {
        $objectType = "group";
        $hostname = $word[2];
      } else {
        $objectType = "subnet";
        $hostname = $word[1];
        $netmask = $word[2];
      }
      print("$workDir/network-object-$systemName-$objectType-$hostname -- $objectType -- $systemName $objectType $hostname $netmask");
      printFileLine("$workDir/network-object-$systemName-$objectType-$hostname","$objectType","$systemName $objectType $hostname $netmask","$printVerbose");
      if ( -d "$hostDir/$hostname" ) {
        printFileLine("$hostDir/$hostname/objectGroup-$systemName-$hostname-$objectName","objectGroup","$systemName $objectType $objectName","$printVerbose");
      } else {
        my $eIP = expandIp($hostname);
        my $workDir = "$ipDir/$eIP";
        testMkDir("$ipDir/$eIP");
        printFileLine("$workDir/firewall-$systemName","firewall","$systemName","$printVerbose");
        printFileLine("$workDir/ipaddr","ip address",$hostname,"$printVerbose");
        if ( "$objectType" eq "subnet" ) {
          printFileLine("$workDir/netmask","netmask",$netmask,"$printVerbose");
        }
        printFileLine("$workDir/objectGroup-$systemName-$hostname","objectGroup","$systemName $objectType $objectName","$printVerbose");
      }
    } elsif ( "$word[0]" eq "group-object" ) {
      print("objectType: $objectType.<BR>");
      # support for groups in groups.
      my $groupName = $word[1];
#     print("workDir = $workDir<BR>");
      printFileLine("$workDir/group-object-$systemName-group-$groupName","group-object","$systemName group $groupName","$printVerbose");
      # nog beter nagaan dat het objectType niet aangepast kan worden door sub types (bij zowel ip als group members)
      if (( $objectType eq "ip" ) and ( &testIfIp( $groupName ) ne "oke" )) {
        $objectType = "network";
      }
      my $objectMemberDir = "$objectDir/$objectType/$systemName-=-$groupName";
#     if ( $objectType eq "service" ) {
#       $objectMemberDir = "$objectDir/$objectType/$systemName-=-$groupName";
#     }
      testMkDir("$objectMemberDir");
      print(" $objectMemberDir/objectGroup-$systemName-parent-$objectName -- group-object -- $systemName group $objectName<BR>");
      printFileLine("$objectMemberDir/objectGroup-$systemName-parent-$objectName","group-object","$systemName group $objectName","$printVerbose");
    } elsif ( "$word[0]" eq "access-list" ) {
#     my $accessString = join(' ', @word);
#     print("<PRE>$accessString</PRE>");
      #my $testStr = substr($word[1], -10);
      #printFileLine("$accessGroupDir/$systemName-$aclName","aclInfo","$aclName $direction $what $intName");
      if ( -f "$accessGroupDir/$systemName-$word[1]" ) {
        my $access_info = catFileLine("$accessGroupDir/$systemName-$word[1]");
	my ( $aclName, $direction, $dummy, $intName ) = split(/ /, $access_info);
        my $dispNum = sprintf("%04d", $ruleNum);
        #rint("$dispNum $intName $word[2]<BR>");
        my $workDir = "$ruleDir/rule-$systemName-=-$dispNum";
        testMkDir("$workDir");
        printFileLine("$workDir/direction","Direction","$direction","$printVerbose");
        if ( "$word[2]" eq "extended" ) {
          my $flags = "";
          printFileLine("$workDir/interface","Interface","$intName","$printVerbose");
          shift @word;
          shift @word;
          $ruleNum++;
          $remarkNum = 1;
          my $objectgroup = "no";
          my $direction = "none";
          my $subnet = "no";
          my $portNum = "no";
	  my $range = "no";
          foreach my $param (@word) {
            if ( "$param" eq "extended" ) {
              printFileLine("$workDir/type","type","$param","$printVerbose");
            } elsif (( "$param" eq "permit" ) or ( "$param" eq "deny" )) {
              printFileLine("$workDir/action","action","$param","$printVerbose");
            } elsif (( "$param" eq "tcp" ) or ( "$param" eq "udp" ) or ( "$param" eq "ip" ) or ( "$param" eq "icmp" )) {
              printFileLine("$workDir/protocol","protocol","$param","$printVerbose");
            } elsif (( "$param" eq "log" ) or ( "$param" eq "inactive" ) or ( "$param" eq "debugging" )) {
              $flags = "$flags $param";
            } elsif (( "$param" eq "object-group" ) or ( "$param" eq "object")) {
	      if ( -f "$workDir/action" ) {
                $objectgroup = "group";
	      } else {
	        $objectgroup = "service";
	      }
            } elsif ( "$param" eq "host" ) {
              $objectgroup = "host";
	    } elsif ( "$param" eq "interface" ) {
	      $objectgroup = "interface";
            } elsif ( "$param" eq "any" ) {
              if ( "$direction" eq "none" ) {
                $direction = "in";
              } else {
                $direction = "out";
              }
	      my $testDir = "$ipDir/000.000.000.000";
	      testMkDir("$testDir");
	      printFileLine("$testDir/firewall-$systemName","firewall","$systemName","$printVerbose");
	      printFileLine("$testDir/ipaddr","ipAddress","any","$printVerbose");
              printFileLine("$workDir/traffic-$direction","traffic-$direction","global $param","$printVerbose");
              if ( ! -l "$testDir/rule-$systemName-=-$dispNum" ) {
	        system "ln -s $workDir $testDir/rule-$systemName-=-$dispNum";
              } else {
                print("link for $testDir/rule-$systemName-=-$dispNum already exists<BR>");
              }
            } elsif (( "$objectgroup" eq "group" ) or ( "$objectgroup" eq "host" ) or ( "$objectgroup" eq "interface" ) or ( "$objectgroup" eq "service" )) {
              my $testDir;
#             print("objectgroup=$objectgroup, param=$param");
              if ( "$objectgroup" eq "group" ) {
                $param = splitObject($param);
#               print(" splitObject=$param ");
                $testDir = "$objectDir/network/$systemName-=-$param";
              } elsif ( "$objectgroup" eq "host" ) {
                #print ("host=$param.<BR>");
                if ( !-d "$hostDir/$param" ) {
                  $objectgroup = "ip";
                  my $eIP = expandIp($param);
                  $testDir = "$ipDir/$eIP";
                  # soms worden ip's gebruikt die niet gedefinieerd zijn als object.
                  testMkDir("$testDir");
                  printFileLine("$testDir/firewall-$systemName","firewall","$systemName","$printVerbose");
                  printFileLine("$testDir/ipaddr","ipAddress","$param","$printVerbose");
                } else {
                  $testDir = "$hostDir/$param";
                }
              }
              if ( -d "$serviceDir/$systemName-=-$param" ) {
	        print("Found service $param.\n");
                printFileLine("$workDir/service-$direction","service-$direction","service $param","$printVerbose");
                system "ln -s $workDir $serviceDir/$systemName-=-$param/rule-$systemName-=-$dispNum";
                if ( ! -f "$workDir/protocol") {
                  my $protoType = catFileLine("$serviceDir/$systemName-=-$param/object-protocol-$systemName");
                  printFileLine("$workDir/protocol", "protoType $systemName $param", $protoType);
                }
              } elsif (( -d "$testDir" ) or ( "$objectgroup" eq "interface" )) {
                if ( "$direction" eq "none" ) {
                  $direction = "in";
                } else {
                  $direction = "out";
                }
                #print("<BR>network $param $direction<BR>");
                if ( ! -f "$workDir/traffic-$direction" ) {
                  printFileLine("$workDir/traffic-$direction","int_traffic-$direction","$objectgroup $param","$printVerbose");
                } else {
                  printFileLine("$workDir/service-$direction","int_service-$direction","service $param","$printVerbose");
                }
		if ( "$testDir" ne "" ) {
                  system "ln -s $workDir $testDir/rule-$systemName-=-$dispNum";
		}
              } elsif ( -d "$serviceDir/$systemName-=-$param" ) {
                # Mag weg als bovenstaande regel werkt.
                printFileLine("$workDir/service-$direction","service-$direction","service $param","$printVerbose");
                #system "ln -s $serviceDir/$param/rule-$systemName-$dispNum $workDir";
                if ( !-d "$serviceDir/$systemName-=-$param" ) { 
                  print("Oops, no $serviceDir/$systemName-=-$param\n"); 
                } else {
                  system "ln -s $workDir $serviceDir/$systemName-=-$param/rule-$systemName-=-$dispNum";
                }
              } else {
                print("acl: $param.<BR>");
              }
              $objectgroup = "no"
            } elsif ( "$subnet" ne "no" ) {
	      printFileLine("$workDir/traffic-$direction","noSub_traffic-$direction","subnet $subnet $param","$printVerbose");
	      testMkDir("$hostDir/$subnet");
	      system "ln -s $workDir $hostDir/$subnet/rule-$systemName-=-$dispNum";
	      if ( testIpAddr $subnet ) {
	        #####
		my $eIP = expandIp($subnet);
		my $testDir = "$ipDir/$eIP";
		if ( ! -f "$testDir/hostname-$systemName-=-$subnet" ) {
		  testMkDir("$testDir");
		  printFileLine("$testDir/firewall-$systemName","Firewall","$systemName","$printVerbose");
		  printFileLine("$testDir/hostname-$systemName-=-$subnet","Firewall","$subnet","$printVerbose");
		}
	      }
	      $subnet = "no";
	    } elsif (( -d "$hostDir/$param" ) or ( testIpAddr $param )) {
              if ( "$direction" eq "none" ) {
                $direction = "in";
              } else {
                $direction = "out";
              }
              $subnet = "$param";
	    } elsif (( "$param" eq "echo" ) or ( "$param" eq "echo-reply" ) or ( "$param" eq "unreachable" )) {
              # need more work on the above list so we don't need to add all individual services.
	      # use this for individual entries.
	      printFileLine("$workDir/service-$direction","service-$direction","$param","$printVerbose");
            } elsif (( "$param" eq "gt" ) or ( "$param" eq "eq" ) or ( "$param" eq "neq" )) {
              $portNum = "$param";
            } elsif ( "$portNum" ne "no" ) {
              printFileLine("$workDir/service-$direction","service-$direction","port $portNum $param","$printVerbose");
              $portNum = "no";
	    } elsif ( "$param" eq "range" ) {
	      $range = "";
	    } elsif ( "$range" ne "no" ) {
	      if ( "$range" eq "" ) {
	        $range = $param;
	      } else {
	        printFileLine("$workDir/service-$direction","service-$direction","range $range $param"); 
		$range = "no";
	      }
	    } elsif ( "$flags" ne "" ) {
	      $flags = "$flags $param";
            } else {
              print("acl unk: $param <BR>");
            }
          }
          printFileLine("$workDir/flags","Flags","$flags","$printVerbose");
          #print("<BR>");
        } elsif ( "$word[2]" eq "remark" ) {
          my $dispNum = sprintf("%02d", $remarkNum);
          shift @word;
          shift @word;
          shift @word;
          my $remark = join(' ', @word);
          printFileLine("$workDir/remark-$dispNum","remark","$remark","$printVerbose");
          $remarkNum++;
        } else {
          print ("acl-$word[2]- <BR>");
        }
      } else {
        print ("line-$word[0]- <BR>");
      }
    } elsif ( "$word[0]" eq "global" ) {
      my $intName = $word[1];
      $intName = remBrackets($intName);
      my $refNum = $word[2];
      my $entry = $word[3];
      shift @word;
      shift @word;
      shift @word;
      my $info = join(' ', @word);
      #$str =~ s/^(//;
      my $workDir = "$pixNatDir/$systemName-nat-$refNum";
      testMkDir("$workDir");
      printFileLine("$workDir/natted-$intName-$entry","natted","<B>$intName</B>: $info","$printVerbose");
      printFileLine("$workDir/type","type","$systemName nat","$printVerbose");
    } elsif ( "$word[0]" eq "nat" ) {
      my $intName = $word[1];
      $intName = remBrackets($intName);
      my $refNum = $word[2];
      my $entry = $word[3];
      shift @word;
      shift @word;
      shift @word;
      my $info = join(' ', @word);
      my $workDir = "$pixNatDir/$systemName-nat-$refNum";
      testMkDir("$workDir");
      printFileLine("$workDir/source-$intName-$entry","source","<B>$intName</B>: $info","$printVerbose");
    } elsif ( "$word[0]" eq "static" ) {
      my $intInfo = $word[1];
      $intInfo = remBrackets($intInfo);
      my ( $orgInt, $natInt ) = split(/,/, $intInfo);
      my $natIp = $word[2];
      shift @word; shift @word; shift @word;
      my $orgIp = join(' ', @word);
      my $workDir = "$pixNatDir/$systemName-static-$natIp";
      testMkDir("$workDir");
      printFileLine("$workDir/source-static","source","<B>$orgInt</B>: $orgIp","$printVerbose");
      printFileLine("$workDir/natted-static","natted","<B>$natInt</B>: $natIp","$printVerbose");
      printFileLine("$workDir/type","type","$systemName static","$printVerbose");
    } elsif ( "$word[0]" eq "" ) {
      print("$word[1]_$word[2]_$word[3]_$word[4]");
    } else {
      print ("-$word[0]- <BR>");
    }
  }
}

sub remBrackets {
  my $var = "@_[0]";
  $var =~ s/^\(//;
  $var =~ s/\)$//;
  return $var;
}

sub runPrintInterfaces {
  if ( -d $interfaceDir ) {
    chdir $interfaceDir;
    my @ints = <*>;
    foreach my $intName (@ints) {
      my @ipEntries = <$intName/ipaddr-*>;
      foreach my $ipInstance (@ipEntries) {
        my $ipInfo = catFileLine("$ipInstance");
	my ( $firewall, $ipaddr, $mask ) = split(' ', $ipInfo);
	my $vlanInfo = catFileLine("$intName/vlan-$firewall");
	my $standbyInfo = catFileLine("$intName/standby-$firewall");
	my $seclevelInfo = catFileLine("$intName/seclevel-$firewall");
	# seclevel-fwsm-management  standby-fwsm-management  vlan-fwsm-management
	print("<TR><TD>$intName</TD>
	           <TD>$firewall</TD><TD>$vlanInfo</TD>
		   <TD>$ipaddr</TD>
		   <TD>$mask</TD>
		   <TD>$standbyInfo</TD>
		   <TD>$seclevelInfo</TD></TR>");
      }
    }
  }
}

sub runPrintIps {
  if ( -d $ipDir ) {
    chdir $ipDir;
    my @ips = <*>;
    foreach my $eIpAddr (@ips) {
      my $ipAddr = catFileLine("$ipDir/$eIpAddr/ipaddr");
    #<A HREF=$httpScriptName?fwan+analyse+$firewall>analyse</A>
      my $ipColor = getNodeColor( $ipAddr );
      print("<TR VALIGN=top BGCOLOR=#FFDDDD>
              <TD ALIGN=right BGCOLOR=$ipColor><A HREF=$httpScriptName?mon+nodestatus+$ipAddr>$ipAddr</A></TD><TD>");
      my @firewallList = <$ipDir/$eIpAddr/firewall-*>;
      foreach my $fwEntry (@firewallList) {
        my $fwName = catFileLine("$fwEntry");
        print("<A HREF=$httpScriptName?fwan+analyseIp+$fwName+$eIpAddr>$fwName</A> ");
        my @hostFiles =  <$ipDir/$eIpAddr/hostname-$fwName-=-*>;
        foreach my $dirEntry (@hostFiles) {
          my $hostname = catFileLine("$dirEntry");
	  print("$hostname ");
        }
        print("<BR>");
      }
      print("</TD></TR>");
    }
  } else {
    print ("Oops, no ip-dir ($ipDir) found, run analyse first....");
  }
}

sub getDnsInfo {
  my $ipAddr = "@_[0]";
  my $ipNodeDir = getIpDir( $ipAddr );
  my $dnsInfo = catFileLine("$ipNodeDir/dnsname.txt");
  if ( $dnsInfo ne "" ) {
    my ( $type, $host, $domain ) = split(' ', $dnsInfo);
    return( "$host.$domain" );
  }
}

sub getComment {
  my $ipAddr = "@_[0]";
  my $ipNodeDir = getIpDir( $ipAddr );
  my $comment = catFileLine("$ipNodeDir/comment.txt");
  return( $comment );
}


sub runFirewallIps {
  my $firewall = "@_[0]";
  if ( -d $ipDir ) {
    chdir $ipDir;
    my @ips = <*>;
    foreach my $eIpAddr (@ips) {
      if ( -f "$ipDir/$eIpAddr/firewall-$firewall" ) {
        my $ipAddr = catFileLine("$ipDir/$eIpAddr/ipaddr");
        my $ipColor = getNodeColor( $ipAddr );
        print("<TR VALIGN=top BGCOLOR=#FFDDDD>
                 <TD ALIGN=right BGCOLOR=$ipColor><A HREF=$httpScriptName?mon+nodestatus+$ipAddr>$ipAddr</A></TD><TD>");
        my @hostFiles =  <$ipDir/$eIpAddr/hostname-$firewall-=-*>;
        my $info = "";
        my $lastEntry; # use this to filter duplicate entries in case of overlapping firewall names.
        foreach my $dirEntry (@hostFiles) {
          my $hostname = catFileLine("$dirEntry");
          if ( $hostname ne $lastEntry ) {
            if ( "$info" ne "" ) { $info = "$info...<BR>"; }
            $info = "$info fw:$hostname";
            if ( $hostname ne "" ) {
              if ( -f "$hostDir/$hostname/description-$firewall" ) {
                my $description = catFileLine("$hostDir/$hostname/description-$firewall");
                $info = "$info: $description";
              }
            }
            $lastEntry = $hostname;
          }
        }
        my $dnsInfo = getDnsInfo( $ipAddr );
        if ( "$dnsInfo" ne "" ) {
          if ( "$info" ne "" ) { $info = "$info<BR>"; }
          $info = "$info dns:$dnsInfo";
          my $comment = getComment( $ipAddr );
          if ( $comment ne "" ) { $info = "$info<BR>comment: $comment"; }
        } 
        print("$info</TD></TR>");
      }
    }
  } else {
    print ("Oops, no ip-dir ($ipDir) found, run analyse first....");
  }
}


sub getHostIp {
  my $firewall = "@_[0]";
  my $hostName = "@_[1]";
  my @ipEntries = <$hostDir/$hostName/ipaddr-$firewall-*>;
  my $info = catFileLine("$ipEntries[0]");
  my ( $dummy, $ipAddr) = split(' ', $info);
  return("$ipAddr");
}

sub printUrl {
  my $param = "@_[0]";
  my ( $firewall, $type, $name, $rest ) = split(' ', $param);
  if ( "$type" eq "ip" ) {
    my $eIP = expandIp($name);
    if ( "$eIP" ne "000" ) {
      return "$type <A HREF=$httpScriptName?fwan+analyseIp+$firewall+$eIP>$name</A>";
    } else {
      return($name);
    }
  } elsif ( "$type" eq "host" ) {
    return "$type <A HREF=$httpScriptName?fwan+analyseHost+$firewall+$name>$name</A>";
  } elsif ( "$type" eq "group" ) {
    return "$type <A HREF=$httpScriptName?fwan+analyseGroup+$firewall+$name>$name</A>";
  } elsif ( "$type" eq "subnet" ) {
    my $ipAddr = getHostIp("$firewall", "$name");
    return "$type <A HREF=$httpScriptName?fwan+analyseHost+$firewall+$name>$name</A> $ipAddr $rest";
  } elsif (( "$type" eq "global" ) or ( "$type" eq "interface" )) {
    return "$type <B>$name</B>";
  } elsif ( "$type" eq "" ) {
    return "syntax <B><FONT COLOR=red>error</FONT></B>";
  } else {
    return($param);
  }
}

sub dispService {
  my $serviceOut = "@_[0]";
  my ( $outType, $outService ) = split(/ /, $serviceOut);
  if ( "$outType" eq "service" ) {
    $serviceOut = ("$outType <A HREF=$httpScriptName?fwan+analyseService+$firewall+$outService>$outService</A>");
  }
  return($serviceOut);
}

sub extractBgColor {
  my $info = "@_[0]";
  my $defBgColor = "@_[1]";
  my ( $type, $ipAddr, $rest ) =  split(' ', $info );
  my $bgColor;
  if ( "$type" eq "ip" ) {
    $bgColor = getNodeColor( $ipAddr );
  } else {
    $bgColor = $defBgColor;
  }
  return $bgColor;
}

sub testSrcDst {
  my $fwName = "@_[0]";
  my $testIp = "@_[1]";
  my $addrInfo = "@_[2]";
  my $return;
# print(", addrInfo: $addrInfo");
  my ( $type, $info1, $info2 ) = split(' ', $addrInfo);
  if (( $type eq "global" ) and ( $info1 eq "any" )) {
    $return = "oke";
  } elsif ( $type eq "group" ) {
    my @ipAddrRecs = <$objectDir/network/$fwName-=-$info1/network-object-$fwName-*>;
    foreach my $ipEntry (@ipAddrRecs) {
#     print(", ipEntry: $ipEntry");
      my $ipInfo = catFileLine($ipEntry);
#     print(", ipInfo: $ipInfo");
      my ( $eFwName, $eType, $eInfo1, $eInfo2 ) = split(' ', $ipInfo);
#     print(", eType: $eType");
      if (( $eType eq "ip" ) and ( $eInfo1 eq $testIp )) {
        $return = "oke";
      } elsif ( $eType eq "group" ) {
        print(", group: $eType $info1");
        $return = testSrcDst( $fwName, $testIp, "$eType $info1");
      } elsif ( $eType eq "subnet" ) {
#       print(" $info1 eType: $eType, $eInfo1, $eInfo2.");
        my $broadcast = calcIpNet($eInfo1, $eInfo2, "broadcast");
        my $test = testBetween( $testIp, $eInfo1, $broadcast );
        if ( $test eq "xxxx" ) {
          $return = "oke";
#         print(" oke ");
        }
      } elsif (( $eType ne "ip" ) and ( $eType ne "group" )) {
        # test to find other types defined.
#       print(", <B>eType: $eType, eInfo1: $eInfo1</B>");
      }
      if ( $return eq "oke" ) { 
        last;
       }
    }
    if ( $return ne "oke" ) {
      my @groupRecs = <$objectDir/network/$fwName-=-$info1/group-object-$fwName-group-*>;
      foreach my $groupEntry (@groupRecs) {
        my $groupInfo = catFileLine($groupEntry);
        my ( $eFwName, $eType, $eInfo1, $eInfo2 ) = split(' ', $groupInfo);
        if ( $eType eq "group" ) {
          $return = testSrcDst( $fwName, $testIp, "$eType $eInfo1");
          if ( $return eq "oke" ) {
            last;
          }
        }
      }
    }
  } elsif ( $type eq "ip" ) {
    if ( $info1 eq $testIp ) {
      $return = "oke";
    }
  } elsif ( $type eq "subnet" ) {
    my $broadcast = calcIpNet($info1, $info2, "broadcast");
    my $test = testBetween( $testIp, $info1, $broadcast );
    if ( $test eq "xxxx" ) {
      $return = "oke";
    }
  } else {
    print("testSrcDst: <B>type $type not defined ( $info1, $info2 ).</B>");
  }
# if ( $return eq "oke" ) {
#   print("<B>testIp = oke</B> ");
# }
  return $return;
}

sub testSrv {
  my $fwName = "@_[0]";
  my $testSrv = "@_[1]";
  my $srvInfo = "@_[2]";
  my $return;
# print(", srvInfo: $srvInfo, testSrv: $testSrv");
  my ( $srvType, $srvName ) = split(' ', $srvInfo);
  my @servList = <$objectDir/service/$fwName-=-$srvName/service-*>;
  foreach my $srvRec (@servList) {
#   print(", srvRec: $srvRec");
    my $recInfo = catFileLine("$srvRec");
#   print(", recInfo: $recInfo");
    my ( $testFw, $testRec ) = split(' ', $recInfo);
    my ( $type, $val1, $val2, $val3 ) = split('_', $testRec);
    if (( "$type $val1" eq "port eq" ) and ( $testSrv eq $val2 )) {
      $return = "oke";
      last;
    } elsif (( "$type $val1" eq "port range" ) and ( $testSrv >= $val2 ) and ( $testSrv <= $val3 )) {
#     print(" <B>testSrv: range oke ($testSrv, $val2, $val3)</B>");
      $return = "oke";
      last;
    } elsif (( "$type $val1" ne "port eq" ) and ( "$type $val1" ne "port range" )) {
      print(" <B>testSrv: $type $val1 $val2</B> ");
    }
  }
  return $return;
}

sub testRuleHit {
  # test if a traffic pattern matches an fw rule.
  my ( $fwName, $line, $sourceInt, $proto, $sourceIp, $destIp, $destPort ) = @_;
  my $result;
# print("testRuleHit: $sourceInt<BR>");
  my $action = catFileLine("$line/action");
# if ( $action eq "permit") {
    my $ruleInt = catFileLine("$line/interface");
    if ( $ruleInt eq $sourceInt ) {
#     print("ruleInt: $ruleInt");
      my $ruleProto = catFileLine("$line/protocol");
      if (( $ruleProto eq "ip" ) or ( $ruleProto eq $proto ) or (( $ruleProto eq "tcp-udp" ) and (( $proto eq "tcp" ) or ( $proto eq "udp")))) {
#       print("<BR>ruleProto: $ruleProto");
        my $trafIn = catFileLine("$line/traffic-in");
        my $inResult = testSrcDst($fwName, $sourceIp, $trafIn);
#       print(", trafIn: $trafIn");
        if ( $inResult eq "oke") {
#         print(", inResult: $sourceIp");
          my $trafOut = catFileLine("$line/traffic-out");
          my $outResult = testSrcDst($fwName, $destIp, $trafOut);
          if ( $outResult eq "oke") {
#           print(", outResult: $outResult");
            if ( -f "$line/service-out" ) {
              my $service = catFileLine("$line/service-out");
#             print(", service: $service");
              my $srvResult = testSrv($fwName, $destPort, $service);
              if ( $srvResult eq "oke" ) {
                $result = "oke";
#               print(" <B>testRuleHit: hit</B> ");
              }
            } else {
              # if no out service is defined, thats also oke.
              $result = "oke";
            }
          }
        }
      }
    }
# }
# print("<BR>");
  return($result);
}

sub analyseTraffic {
  print("</CENTER>");
  my $fwName = "@_[0]";
  my $lcFwName = lc($fwName);
  testMkDir("$unmatchedTrafDir/$fwName");
  my %hit; # make sure hits are only processed once.
  # first find the device type (to get an ip addr, to get the syslog name).
  my @devDirs = <$SIMparam{'SIMdeviceDir'}/*>;
  my ( $logDevName, $logDir );
  foreach my $entry (@devDirs) {
    if ( -f "$entry/$lcFwName/ipaddr" ) {
#     printDebug(0, "analyseTraffic: devDirs entry=$entry");
      my $manIp = catFileLine("$entry/$lcFwName/ipaddr");
      ( $logDevName, $logDir ) = getLoggingInfo($manIp);
#     printDebug(0, "analyseTraffic: manIp = $manIp, logDevName = $logDevName");
      last;
    }
  }

  # create trafficanalyser info.
  chdir "$SIMparam{'SIMsyslogDir'}";
  if ( $logDevName eq "" ) {
    print("No entry found for $fwName in the SIMdeviceDir (device not managed?), use the traffic analyser to analyse traffic manualy.");
  } else {
    my @possibleDirs = <*>;
    printDebug(1, "analyseTraffic: looking in $SIMparam{'SIMsyslogDir'}.");
    foreach my $dirEntry (@possibleDirs) {
      printDebug(1, "analyseTraffic: test possibleDirs $dirEntry for $fwName.");
      if ( -d "$dirEntry/$logDevName" ) {
        # test if the data is already analysed ( data whisch was analysed on the date it was created, will be reanalysed).
        my $testDate = substr($dirEntry, -10);
        my $dirDateNum = (stat "$SIMparam{'SIMtrafficAnalyserDir'}/$dirEntry/$logDevName" )[9];
        my $dirDate = printDate( $dirDateNum, "yyyymmdd" );
#       print(" $testDate, $dirDateNum, $dirDate ");
        if (( ! -d "$SIMparam{'SIMtrafficAnalyserDir'}/$dirEntry/$logDevName" ) or ( $testDate eq $dirDate )) {
          analyseSyslog("dummy", $dirEntry, $logDevName);
        } else {
          print("<B>data for $logDevName, $dirEntry already analysed on $dirDate</B>.<BR>");
        }
      }
    }
  }

  # process trafficanalyser info.
  chdir "$SIMparam{'SIMtrafficAnalyserDir'}";
  my @syslogDirs = <*>;
  @syslogDirs = reverse(@syslogDirs);
  print("Analysing: $fwName<BR>");
  my @rules = <$ruleDir/rule-$fwName-=-*>;
  # remove old traffic info before reanalyse.
  foreach my $line (@rules) {
#   print("line=$line<BR>");
    my @oldTrafInfo = <$line/trafficFlow-*>;
    foreach my $entry (@oldTrafInfo) {
      if ( -f $entry ) {
        unlink($entry);
      } else {
        print(" <B>Oops, problem removing $entry.</B> ");
      }
    }
  }
  foreach my $syslogDir ( @syslogDirs ) {
    chdir "$SIMparam{'SIMtrafficAnalyserDir'}/$syslogDir";
#   system(" pwd ");
    my @nameList = <$lcFwName.*>;
    foreach my $fwTestName ( @nameList ) {
      my ( $testName, $rest ) = split('\.', $fwTestName);
#     print("testName: $testName<BR>");
      if ( $testName eq $lcFwName ) {
        print(" $syslogDir");
        my @sourceList = <$SIMparam{'SIMtrafficAnalyserDir'}/$syslogDir/$fwTestName/source/*>;
        foreach my $sourceIp ( @sourceList ) {
#         print("sourceIp: $sourceIp<BR>");
          my @trafList = <$sourceIp/*>;
          foreach my $trafEntry ( @trafList ) {
            open(IN, $trafEntry);
            my $lastLine;
            while(<IN>) {
              $lastLine = $_ if eof;
            }
            close IN;
#           print("<BR>lastLine: $lastLine ");
            my ( $readType, $data, $time, $sourceIp, $sourcePort, $destIp, $destPort, $proto, $d1, $d2, $d3, $sourceInt )  = split(' ', $lastLine);
#           print("<BR><B>$sourceInt - $proto - $sourceIp - $destIp - $destPort</B><BR>");
            # test if rule has been tested (in case of analysing multiple day's.
            my $hitName = "$sourceIp-$destIp-$destPort-$proto";
            if ( $hit{$hitName} eq "" ) {
              $hit{$hitName} = "$syslogDir";
              # process all rules for each traffic entry
              my $outDir = "$unmatchedTrafDir/$fwName";
              foreach my $line (@rules) {
                my $flags = catFileLine("$line/flags");
                my ( $inact, $rest ) = split(' ', $flags);
                # don't test inactive line.
                if ( $inact ne "inactive" ) {
#                 print("<BR>$line  ");
                  my $result = testRuleHit($fwName, $line, $sourceInt, $proto, $sourceIp, $destIp, $destPort);
                  if ( $result eq "oke" ) {
                    $outDir = $line;
#                   print(" <BR><B>LINE OKE</B> $line<BR> ");
                    last;
                  }
                }
              }
              my $longSourceIp = expandIp($sourceIp);
              my $longDestIp = expandIp($destIp);
              my $longDestPort = expandIp($destPort);
              printFileLine("$outDir/trafficFlow-$longSourceIp-$longDestIp-$proto-$longDestPort","quiet","$syslogDir $fwTestName $sourceInt $sourceIp $destIp $proto $destPort $time");
#           } else {
#             print(" $hitName skipped. ");
            }
          }
        }
      }
    }
  }
  printFileLine("$SIMparam{'SIMtmpDir'}/traffic-analysed-$fwName", "quiet", time);
  print("<CENTER>");
}

sub displaySubServices {
  my $evalService = "@_[0]";
  my ( $testService, $testName ) = split(' ', $evalService);
  if ( $testService eq "service" ) {
    my $serviceInfo = &printServiceLine("$serviceDir/$firewall-=-$testName", "return");
    my $dispServiceOut = dispService("$evalService");
    $evalService = "<B>$dispServiceOut</B> <BR> $serviceInfo";
    #print("<TR><TD COLSPAN=99>serviceOut = $serviceOut</TD></TR>");
  }
  return($evalService);
}

sub displayGroupMembers {
  my $evalGroup = "@_[0]";
  my ( $testType, $testName ) = split(' ', $evalGroup);
# print("<TR><TD COLSPAN=99>testType: $testType, testName: $testName.</TD></TR>");
  my $groupInfo = runAnalyseGroup("$testName", "detail", "returnMembers");
  if ( $groupInfo ne "" ) {
    $evalGroup = printUrl("$firewall $evalGroup");
    $evalGroup = "<B>$evalGroup</B>$groupInfo";
  }
  return($evalGroup);
}

sub displayRule {
  my $dirlist = "@_[0]";
  my $option = "@_[1]";
  my $parameter = "@_[2]";
  my %portCache;
  my ( $rType, $rParameter );
  # read the iana port names.
  open( IANA, $SIMparam{'SIMianaPorts'} );
  my @ianaInfo = <IANA>;
  close(IANA);
  if ( "$option" eq "report" ) {
    ( $rType, $rParameter ) = split(/=/, $parameter);
  }
  #print("<TR BGCOLOR=#DDDDDD><TD COLSPAN=10>dirlist=$dirlist, option=$option, parameter=$parameter</TD></TR>");
  my @ruleEntries = <$dirlist-=-*>;
  foreach my $dirEntry (@ruleEntries) {
    #print("<TR BGCOLOR=#DDDDDD><TD COLSPAN=10>dirEntry=$dirEntry</TD></TR>");
    #action  protocol  remark-01  rule-fwsm-ebacc-0070  service-in  service-out  traffic-in  traffic-out  type
    my $remarks;
    my @remarkEntries = <$dirEntry/remark-*>;
    foreach my $remarkEntry (@remarkEntries) {
      my $remInfo = catFileLine("$remarkEntry");
      if ( "$remarks" eq "" ) {
        $remarks = "$remInfo";
      } else {
        $remarks = "$remarks, $remInfo";
      }
    }
    if (( "$remarks" ne "" ) and (( "$option" eq "detail") or ( "$option" eq "hits" ) or ( "$option" eq "members" ))) {
      print("<TR BGCOLOR=#DDDDDD><TD COLSPAN=2>Comment</TD><TD></TD><TD COLSPAN=10>$remarks</TD></TR>");
    }
    my $interface = catFileLine("$dirEntry/interface");
    my $direction = catFileLine("$dirEntry/direction");
    my $action = catFileLine("$dirEntry/action");
    my $type = catFileLine("$dirEntry/type");
    my $protocol = catFileLine("$dirEntry/protocol");
    my $trafficIn = catFileLine("$dirEntry/traffic-in");
    my $inBgColor = extractBgColor( $trafficIn, "white" );
    my $serviceIn = catFileLine("$dirEntry/service-in");
    my $trafficOut = catFileLine("$dirEntry/traffic-out");
    my $outBgColor = extractBgColor( $trafficOut, "white" );
    my $serviceOut = catFileLine("$dirEntry/service-out");
    my $flags = catFileLine("$dirEntry/flags");
    if ( "$serviceOut" eq "" ) {
      $serviceOut = catFileLine("$dirEntry/service-none");
    }
    if (( "$option" eq "members" ) or ( "$option" eq "hits" )) {
      # display sub members
      $trafficIn = &displayGroupMembers($trafficIn);
      $serviceIn = &displaySubServices($serviceIn);
      $trafficOut = &displayGroupMembers($trafficOut);
      $serviceOut = &displaySubServices($serviceOut);
    } else {
      $trafficIn = printUrl("$firewall $trafficIn");
      $serviceIn = dispService("$serviceIn");
      $trafficOut = printUrl("$firewall $trafficOut");
      $serviceOut = dispService("$serviceOut");
    }
    my $actionColor;
    if (( "$action" eq "permit" ) or ( "$action" eq "pass" ) or ( "$action" eq "xpass" )) {
      $actionColor = "00FF66";
    } elsif ( "$action" eq "deny" ) {
      $actionColor = "FF6600";
    } else {
      $actionColor = "FF0066";
    }
    if ( $action ne "" ) {
      print("<TR BGCOLOR=#EEEEEE VALIGN=top><TD>Rule</TD>
               <TD>$interface</TD>
               <TD>$direction</TD>
               <TD BGCOLOR=#$actionColor>$action</TD>
               <TD>$protocol</TD>
               <TD BGCOLOR=$inBgColor>$trafficIn</TD>
               <TD>$serviceIn</TD>
               <TD BGCOLOR=$outBgColor>$trafficOut</TD>
               <TD>$serviceOut</TD>
               <TD>$flags</TD>
      </TD></TR>");
      if ( "$option" eq "hits" ) {
        # display the hit info
        my @hitList = <$dirEntry/trafficFlow-*>;
        foreach my $entry (@hitList) {
          my $hitInfo = catFileLine($entry);
          my ( $syslog, $syslogFwName, $sourceInt, $sourceIp, $destIp, $proto, $port, $time ) = split(' ', $hitInfo);
          my $sourceName = getLongName($sourceIp);
          my $longSourceIp = longIp($sourceIp);
          my $destName = getLongName($destIp);
          my $longDestIp = longIp($destIp);
          my $longPort = sprintf("%05d", $port);
          $longPort = "$longPort-$proto";
          if ( $portCache{$port} eq "" ) {
            my @portInfo = grep(/ $port\/$proto /, @ianaInfo);
            if ( "$portInfo[0]" ne "" ) {
              my ( $protName, $rest ) = split(' ', $portInfo[0]);
              $portCache{$port} = $protName;
#             print("<TR><TD COLSPAN=3>$port-$proto = $portCache{$port} - $protName");
            } else {
              $portCache{"$port-$proto"} = "-";
            }
          }
#         print("<TR><TD COLSPAN=3></TD><TD COLSPAN=6>$hitInfo</TD></TR>");
          print("<TR BGCOLOR=#FFFFDD><TD>Hit</TD>
                     <TD>$sourceInt</TD>
                     <TD COLSPAN=2></TD>
                     <TD>$proto</TD>
                     <TD><A HREF=$httpScriptName?extra+trafficAnalyser+display+$syslog+$syslogFwName+source+$longSourceIp>$sourceIp</A> $sourceName</TD>
                     <TD></TD>
                     <TD><A HREF=$httpScriptName?extra+trafficAnalyser+display+$syslog+$syslogFwName+dest+$longDestIp>$destIp</A> $destName</TD>
                     <TD><A HREF=$httpScriptName?extra+trafficAnalyser+display+$syslog+$syslogFwName+port+$longPort>$port</A> $portCache{$port}</TD>
                     <TD>$syslog $time</TD></TR>");
        }
      } elsif (( "$option" eq "report" ) and ( "$rType" eq "group" )) {
        my ( $inType, $inName ) = split (/ /, $trafficIn);
        my ( $outType, $outName ) = split (/ /, $trafficOut);
        if (( "$inType" eq "group" ) and ( "$inName" eq "$rParameter" ) and ( "$outType" eq "group" )) {
          my $test = "dummy";
        }
      }
    }
  }
}

sub runAnalyseIp {
  my $eIpAddr = "@_[0]";
  my $report = "@_[1]";
  my $workDir = "$ipDir/$eIpAddr";
  my $ipAddr = catFileLine("$workDir/ipaddr");
  my ( $type, $netmask );
  if ( -f "$workDir/netmask" ) {
    $netmask = catFileLine("$workDir/netmask");
  } else {
    $netmask = "255.255.255.255";
  }
  if ( "$netmask" ne "255.255.255.255" ) {
    print("<TR><TD>Subnet</TD><TD COLSPAN=4>$ipAddr netmask $netmask</TD></TR>");
  } else {
    my $statusColor = getNodeColor( $ipAddr );
    print("<TR><TD><A HREF=$httpScriptName?mon+nodestatus+$ipAddr>Address</A></TD><TD BGCOLOR=$statusColor>$ipAddr</TD></TR>");
  }
  displayRule("$ipDir/$eIpAddr/rule-$firewall");
  my @hostFiles =  <$ipDir/$eIpAddr/hostname-$firewall-=-*>;
  foreach my $dirEntry (@hostFiles) {
    my $hostname = catFileLine("$dirEntry");
    runAnalyseHost("$hostname","$report");
  }
# print("<TR><TD COLSPAN=10>groupFiles: $ipDir/$eIpAddr/objectGroup-$firewall-*</TD></TR>");
  my @groupFiles = <$ipDir/$eIpAddr/objectGroup-$firewall-*>;
  foreach my $dirEntry (@groupFiles) {
    my $groupReccord = catFileLine("$dirEntry");
    my ( $dummy, $dummy2, $groupName) = split(' ', $groupReccord);
    runAnalyseGroup("$groupName","$report");
  }
}

sub runAnalyseHost {
  my $hostname = "@_[0]";
  my $report = "@_[1]";
  my $ipInfo;
  if ( ! -d "$hostDir/$hostname" ) {
    # als het toch geen hostnaam is, dan is het een ip adres.
    my $eIpAddr = &expandIp($hostname);
    &runAnalyseIp($eIpAddr, $report);
  } else {
  my @ipEntries = <$hostDir/$hostname/ipaddr-$firewall-*>;
  foreach my $entry (@ipEntries) {
    my $info = catFileLine($entry);
    my ( $dummy, $ipAddr) = split(' ', $info);
    my $url = printUrl("$firewall ip $ipAddr");
    my $description = catFileLine("$hostDir/$hostname/description-$firewall");
    $ipInfo = "$ipInfo $url $description";
  }
  print("<TR BGCOLOR=#FFDDDD><TD>Hostname</TD><TD COLSPAN=3>$hostname</TD><TD COLSPAN=6>$ipInfo</TD></TR>");
  my @objectRecs = <$hostDir/$hostname/objectGroup-$firewall-*>;
  displayRule("$hostDir/$hostname/rule-$firewall");
  foreach my $objectentry (@objectRecs) {
    my $objectRec  = catFileLine("$objectentry");
    my ( $dummy, $type, $groupName ) = split(' ', $objectRec);
    runAnalyseGroup("$groupName","$report");
  }
  }
}

sub runAnalyseGroup {
  # groepen met subgroepen analyseren.
  my $groupName = "@_[0]";
  my $option = "@_[1]";
  my $output = "@_[2]";
  # output, to be able to just return the data of sub menmbers.
  my $memberInfo;
# print("<TR><TD COLSPAN=4>runAnalyseGroup groupName=$groupName, option=$option, output=$output.</TD></TR>");
  my $groupDescription = catFileLine("$objectDir/network/$firewall-=-$groupName/description-$firewall");
  my ($dispCagegory, $dispColor);
  if ( "$option" eq "list" ) {
    $dispCagegory = "Subgroup"; 
    $dispColor = "88FFFF";
  } else {
    $dispCagegory = "Groupname";
    $dispColor = "00EEEE";
  }
  if ( $output ne "returnMembers" ) {
    print("<TR BGCOLOR=#$dispColor><TD>$dispCagegory</TD><TD COLSPAN=10>$groupName ($groupDescription)</TD></TR>");
  }
  #if (( "$option" eq "detail" ) or ( "$option" eq "list" ) or ( "$option" eq "returnMembers" )) {
  if (( "$option" eq "detail" ) or ( "$option" eq "list" )) {
    # !!!!!!!!!!!!!! nog nagaan of ook ip's binnen de groep weer gedisplayed worden.
    my @hostList = <$objectDir/network/$firewall-=-$groupName/network-object-$firewall-*>;
    foreach my $entry (@hostList) {
      my $hostInfo = catFileLine($entry);
      my ( $dummy, $type, $name, $subnet ) = split(' ', $hostInfo);
      #my $ipColor = getNodeColor( $ipAddr );
      $hostInfo = printUrl("$firewall $type $name $subnet");
      my $memColor = "";
      if ( "$type" eq "ip" ) {
        if ( $output eq "returnMembers" ) {
          my $hostName = &dispHostName( $name, "data");
          $memberInfo = "$memberInfo <BR> $hostInfo $hostName";
        } else {
          $memColor = getNodeColor( $name );
          print("<TR><TD BGCOLOR=$memColor><A HREF=$httpScriptName?mon+nodestatus+$name>Member</A></TD><TD COLSPAN=4>$hostInfo");
        }
      } else {
        if ( $output eq "returnMembers" ) {
          $memberInfo = "$memberInfo <BR> $hostInfo";
        } else {
          print("<TR><TD>Member</TD><TD COLSPAN=4>$hostInfo");
        }
      }
      if ( $output ne "returnMembers" ) {
        if ( "$type" eq "host" ) {
          my @ipEntries = <$hostDir/$name/ipaddr-$firewall-*>;
	  foreach my $entry (@ipEntries) {
	    my $info = catFileLine($entry);
	    my ( $dummy, $ipAddr) = split(' ', $info); 
	    my $url = printUrl("$firewall ip $ipAddr");
	    print("</TD><TD>$url");
	  }
        } elsif ( "$type" eq "ip" ) {
          my $longIp = expandIp($name);
          my @hostNames = <$ipDir/$longIp/hostname-$firewall-=-*>;
          print("</TD><TD>");
          foreach my $entry (@hostNames) {
            my $hostName = catFileLine($entry);
            my $description = catFileLine("$hostDir/$hostName/description-$firewall");
            print("host: $hostName, $description");
          }
        }
      }
      if ( $output ne "returnMembers" ) {
        print("</TD></TR>");
      }
    }
    my @groupList  = <$objectDir/network/$firewall-=-$groupName/group-object-$firewall-group-*>;
    foreach my $entry (@groupList) {
      my $groupInfo = catFileLine($entry);
      my ( $firewall, $type, $group ) = split(' ', $groupInfo);
      #my $returnInfo = runAnalyseGroup( $group, "list" );
      #my $returnInfo = runAnalyseGroup( $group, $option );
      my $returnInfo = runAnalyseGroup( $group, "list", "$output" );
      $memberInfo = "$memberInfo $returnInfo";
    }
  }
# print("<TR><TD COLSPAN=10>option=$option displayRule:$objectDir/network/$firewall-=-$groupName/rule-$firewall</TD></TR>\n");
  if (( "$option" ne "list" ) and ( "$output" ne "returnMembers" )) {
    displayRule("$objectDir/network/$firewall-=-$groupName/rule-$firewall","$option","group=$groupName");
    my @groupList = <$objectDir/network/$firewall-=-$groupName/objectGroup-$firewall-parent-*>;
    foreach my $entry (@groupList) {
      my $groupInfo = catFileLine($entry);
      my ( $dummy, $type, $name ) = split(' ', $groupInfo);
      runAnalyseGroup("$name","$option");
    }
  }
  return($memberInfo);
}

sub runPrintHosts {
  if ( -d "$hostDir" ) {
    chdir($hostDir);
    my @hostList = <*>;
    foreach my $entry (@hostList) {
      my $fwUrl;
      my @ipEntries = <$entry/ipaddr-*>;
      foreach my $ipEntry (@ipEntries) {
        my $catEntry = catFileLine($ipEntry);
	my ( $fwName, $ipAdddr ) = split(' ', $catEntry);
    #return "$type <A HREF=$httpScriptName?fwan+analyseHost+$firewall+$name>$name</A> $ipAddr $rest";
	$fwUrl = "$fwUrl <A HREF=$httpScriptName?fwan+analyseHost+$fwName+$entry>$fwName</A> $ipAdddr<BR>";
      }
      print("<TR VALIGN=top BGCOLOR=#FFFFAA><TD>$entry</TD><TD>$fwUrl</TD><TD></TD><TD></TD></TR>");
    }
  } else {
    print ("Oops, geen hostdir gevonden, run analyse...");
  }
}

sub runPrintGroups {
  my $device = "@_[0]";
  if ( -d "$objectDir/network" ) {
    my @groupList = <$objectDir/network/$device-=-*>;
    foreach my $groupMember (@groupList) {
      my $objectName = catFileLine("$groupMember/object-name");
      my $objectInfo;
      my $objectTypeInfo = catFileLine("$groupMember/object-type-$device");
      my ( $fireWall, $type ) = split(' ', $objectTypeInfo);
      my @rules = <$groupMember/rule-$fireWall-=-*>;
      my $description = catFileLine("$groupMember/description-$fireWall");
      print("<TR BGCOLOR=#AAEEEE>
               <TD>Groupname</TD>
               <TD COLSPAN=2><A HREF=$httpScriptName?fwan+analyseGroup+$fireWall+$objectName>$objectName</A></TD>
	       <TD>$description (" . @rules . " rules)</TD>
	     </TR>");
      my @parentList = <$groupMember/objectGroup-$fireWall-parent-*>;
      foreach my $entry (@parentList) {
        my $info = catFileLine( $entry );
        my ( $fw, $group, $name ) = split(' ', $info);
        my $description = catFileLine("$objectDir/network/$fw-$name/description-$fw");
        print("<TR BGCOLOR=#EEEEAA>
                 <TD BGCOLOR=white></TD><TD>Parentgroup</TD>
                 <TD><A HREF=$httpScriptName?fwan+analyseGroup+$fireWall+$name>$name</A></TD>
                 <TD>$description</TD>
               </TR>");
      }
      my @childList = <$groupMember/group-object-$fireWall-group-*>;
      foreach my $entry (@childList) {
        my $info = catFileLine( $entry );
	my ( $fw, $group, $name ) = split(' ', $info);
	my $description = catFileLine("$objectDir/network/$fw-$name/description-$fw");
	print("<TR BGCOLOR=#EEAAEE>
	         <TD BGCOLOR=white></TD><TD>Childgroup</TD>
		 <TD><A HREF=$httpScriptName?fwan+analyseGroup+$fireWall+$name>$name</A></TD>
		 <TD>$description</TD>
	       </TR>");
      }
      my @objectList = <$groupMember/network-object-$fireWall-*>;
      foreach my $entry (@objectList) {
        my ($hostName, $description);;
        my $info = catFileLine( $entry );
	my ( $fw, $type, $name, $subnet ) = split(' ', $info);
	my $hostInfo = printUrl("$firewall $type $name $subnet");
        my $bgColor = extractBgColor( "$type $name", "#AAAAEE");
	if ( "$type" eq "ip" ) {
	  $hostName = getHostName( $name, $firewall );
	} elsif ( "$type" eq "host" ) {
	  $hostName = $name;
	}
	if ( "$hostName" ne "" ) {
	  $description = catFileLine("$hostDir/$hostName/description-$fw");
	}
	print("<TR BGCOLOR=#AAAAEE>
	         <TD BGCOLOR=white></TD><TD>Entry</TD>
	         <TD BGCOLOR=$bgColor>$hostInfo</TD>
	         <TD>$hostName, $description</TD>
	       </TR>");
      }
      print("<TR><TD></TD></TR>");
    }
  }
}

sub getHostName {
  my $ipAddr = "@_[0]";
  my $fw = "@_[1]";
  my $eIP = expandIp($ipAddr);
  my @hostNames = <$ipDir/$eIP/hostname-$fw-=-*>;
  foreach my $entry (@hostNames) {
    my $hostName = catFileLine( $entry );
    return $hostName;
    last;
  }
}

sub runAnalyseService {
  my $ruleName = "@_[0]";
  my $workDir = "$serviceDir/$firewall-=-$ruleName";
# print("<TR><TD COLSPAN=11>runAnalyseService ruleName=$ruleName</TD></TR>");
  if ( -d "$workDir" ) {
    printServiceLine("$workDir");
    displayRule("$workDir/rule-$firewall");
  }
  # display rules for parent services
  my @parentList = <$serviceDir/$firewall-=-$ruleName/objectGroup-*>;
  foreach my $entry (@parentList) {
    my $info = catFileLine($entry);
    my ( $firewall, $group, $service ) = split(' ', $info);
    print("<TR><TD COLSPAN=11 BGCOLOR=#99FFFF>Parent service <A HREF=$httpScriptName?fwan+analyseService+$firewall+$service>$service</A></TD></TR>");
    displayRule("$serviceDir/$firewall-=-$service/rule-$firewall");
  }
}

sub runPrintServices {
  my @services = <$serviceDir/$firewall-=-*>;
  foreach my $serviceItem (@services) {
    printServiceLine("$serviceItem");
  }
}

sub printServiceLine {
  my $serviceItem = "@_[0]";
  my $outputType = "@_[1]";
  #print("<TR><TD>$serviceItem</TD></TR>");
  my $protocol = catFileLine("$serviceItem/object-protocol-$firewall");
  my $description = catFileLine("$serviceItem/description-$firewall");
  my $objectName = catFileLine("$serviceItem/object-name");
  my $objectType = catFileLine("$serviceItem/object-type-$firewall");
  my ( $dummy , $type ) = split(' ', $objectType );
  my $returnInfo;
  if ( $outputType ne "return" ) {
    print("<TR VALIGN=top BGCOLOR=#CCFFFF>
            <TD COLSPAN=3><A HREF=$httpScriptName?fwan+analyseService+$firewall+$objectName>$objectName</A> ($protocol)</TD>
            <TD COLSPAN=4>$description</TD><TD>");
  }
  my @servList = <$serviceItem/service-$firewall-*>;
  foreach my $servEntry (@servList) {
    my $info = catFileLine("$servEntry");
    my ( $dummy, $info ) = split(/ /, $info);
    $info=~s/_/ /g;
#   print("port $info<BR>");
    if ( $outputType ne "return" ) {
      print("$info<BR>");
    } else {
      $returnInfo = "$returnInfo $info <BR>";
    }
  }
  my @servList = <$serviceItem/group-object-$firewall-group-*>;
  foreach my $servEntry (@servList) {
    my $info = catFileLine("$servEntry");
    my ( $dummy, $type, $info ) = split(/ /, $info);
    $info=~s/_/ /g;
    if ( $outputType ne "return" ) {
      print("$type <A HREF=$httpScriptName?fwan+analyseService+$firewall+$info>$info</A><BR>");
    } else {
      $returnInfo = "$returnInfo $info<BR>";
    }
  }
  if ( $outputType ne "return" ) {
    print("</TD></TR>");
  } else {
    return $returnInfo;
  }
}

sub runReportIps {
# print("<TR><TD>runReportIps, under devellopment</TD></TR>");
  print("<TR BGCOLOR=#DDDDDD><TD VALIGN=top>Type</TD>
             <TD VALIGN=top>Interface<BR>Description</TD>
	     <TD VALIGN=top COLSPAN=2>Direction<BR>Action</TD>
	     <TD>Proto</TD>
	     <TD>Source</TD>
	     <TD>Port</TD>
	     <TD>Destination</TD>
	     <TD>Service</TD>
	     <TD>Option</TD>
	 </TD>");
  chdir $ipDir;
  my @eIpList = <*>;
  foreach my $eIpAddr (@eIpList) {
    if ( -f "$eIpAddr/firewall-$firewall" ) {
      runAnalyseIp("$eIpAddr","host"); 
    }
  }
}

sub runConfList {
  #system("env");
  my $confList = param("confList");
  $confList = lc($confList);
  #print("<BR>confList=$confList, ");
  if ( "$confList" eq "" ) {
    $confList = catFileLine("$confDir/firewall-list");
    #print("confList=$confList, ");
  } else {
    if ( ! -d $confDir ) {
      system("mkdir -p $confDir");
    }
    printFileLine("$confDir/firewall-list","Firewall list","$confList");
  }
  print ("<BR>
      <FORM method=post Action=$httpScriptName?fwan+confList>
      <INPUT NAME=confList Size=60 VALUE=\"$confList\" Type=text>
      <INPUT TYPE=submit Value=Update>
      </FORM> 
      (use all to include all firewall configs for this domain)
      ");
}

sub runPrintPixNat {
  if ( -d $pixNatDir ) {
    print("<TR BGCOLOR=#CCCCCC ALIGN=center><TD COLSPAN=6>Pix, Asa, Fwsm nat table</TD></TR>
           <TR BGCOLOR=#999999>
               <TD>Firewall</TD>
               <TD>Type</TD>
               <TD>Source info</TD>
               <TD>Destination info</TD>
           </TR>");
    my @natEntries = <$pixNatDir/*>;
    my $oldFirewall;
    foreach my $entry (@natEntries) {
      my $info = catFileLine("$entry/type");
      my ($firewall, $type) = split(/ /, $info);
      my @sourceFiles = <$entry/source-*>;
      my @nattedFiles = <$entry/natted-*>;
      my ( $sourceInfo, $nattedInfo );
      foreach my $entry (@sourceFiles) {
        my $info = catFileLine("$entry");
	$sourceInfo = "$sourceInfo $info<BR>";
      }
      foreach my $entry (@nattedFiles) {
        my $info = catFileLine("$entry");
        $nattedInfo = "$nattedInfo $info<BR>";
      }
      if ( "$nattedInfo" ne "" ) {
        printf("<TR BGCOLOR=#EEEEEE VALIGN=top>
                  <TD>$firewall</TD>
                  <TD>$type</TD>
                  <TD>$sourceInfo</TD>
                  <TD>$nattedInfo</TD>
	        </TR>");
      }
    }
  }
}

sub runPrintTunixNat {
  if ( -d $tunixNatDir ) {
    print("<TR BGCOLOR=#DDDDDD ALIGN=center><TD>Tunix nat table</TD>
               <TD>Firewall</TD>
               <TD>from</TD>
               <TD>to</TD>
               <TD>protocol</TD>
               <TD>action</TD>
               <TD>nat source</TD>
               <TD>nat ip</TD>
               <TD>comment</TD>
           </TR>");
    chdir ($tunixNatDir);
    my @natEntries = <*>;
    my ( $oldName, $dispName );
    foreach my $entry (@natEntries) {
      my $dispEntry = $entry;
      my @fwEntries = <$tunixNatDir/$entry/*-service>;
      foreach my $fwEntry (@fwEntries) {
        my $service = catFileLine("$fwEntry");
        my ( $fwName, $servName ) = split(/ /, $service);
        if ( "$oldName" ne "$servName" ) {
          $dispName = $servName;
          $oldName = $servName;
        } else {
          $dispName = "";
        }
        my $natDest = catFileLine("$entry/$fwName-natDest");
        $natDest = printUrl("$fwName ip $natDest");
        my $natSource = catFileLine("$entry/$fwName-natSource");
        $natSource = printUrl("$fwName ip $natSource");
        my $comment = catFileLine("$entry/$fwName-comment");
        my $protocols = catFileLine("$entry/$fwName-protocols");
        my $trafDest = catFileLine("$entry/$fwName-trafDest");
        $trafDest = printUrl("$fwName ip $trafDest");
        my $trafSource = catFileLine("$entry/$fwName-trafSource");
        my @inTrafA = split(/ /, $trafSource);
        $trafSource = "";
        foreach my $item (@inTrafA) {
          #$trafSource = "$item<BR> $trafSource";
          #<A HREF=$httpScriptName?fwan+analyseIp+$fwName+$eIpAddr>$fwName</A>
          $item = printUrl("$fwName ip $item");
          $trafSource = "$item<BR> $trafSource";
        }
        my $action = catFileLine("$entry/$fwName-action");
        #http://10.31.12.198/sipman3-cgi/nph-sipman3.cgi?fwan+analyseIp+gw3a+000.000.000.000
        print("<TR BGCOLOR=#DDFFFF ALIGN=center VALIGN=top><TD>$dispName</TD><TD>$fwName</TD>
               <TD>$trafSource</TD>
               <TD>$trafDest</TD>
               <TD>$protocols</TD>
               <TD>$action</TD>
               <TD>$natSource</TD>
               <TD>$natDest</TD>
               <TD>$comment</TD>
               </TR>");
        $dispEntry = "";
      }
    }
  }
}

sub runReportPolicy {
  print("</TABLE><H2>Firewall rules</H2><TABLE>");
  displayRule("$ruleDir/rule-$firewall", "detail");
  #runPrintRules;
  print("</TABLE><H2>Firewall groups</H2><TABLE>");
  runPrintGroups( $firewall );
  print("</TABLE><H2>Firewall services</H2><TABLE>");
  runPrintServices;
  print("</TABLE><H2>Firewall IP's</H2><TABLE>");
  runFirewallIps( $firewall );
}


# ------------------------------------- Main ---------------------------------------

#&printHeader;
&printFirewalls;
&printMainMenu;
my $timeStamp = catFileLine("$infoDir/lastAnalyse");
my $lastReconfigDate = printDate($timeStamp);
print("<CENTER><B>Context: $firewall</B>, last analyse: $lastReconfigDate<BR><TABLE>");
if ( "$action" eq "analyse" ) {
  print("<TR><TD>");
  runAnalyse;
  print("</TD></TR>");
} elsif ( "$action" eq "confList" ) {
  runConfList;
} elsif ( "$action" eq "analyseIp" ) {
  runAnalyseIp($option1);
} elsif ( "$action" eq "analyseHost" ) {
  runAnalyseHost($option1);
} elsif ( "$action" eq "analyseGroup" ) {
  runAnalyseGroup($option1, "detail");
} elsif ( "$action" eq "analyseService" ) {
  runAnalyseService($option1);
} elsif ( "$action" eq "printInterfaces" ) {
  runPrintInterfaces;
} elsif ( "$action" eq "printTunixNat" ) {
  runPrintTunixNat;
} elsif ( "$action" eq "printPixNat" ) {
  runPrintPixNat;
} elsif ( "$action" eq "printIps" ) {
  runPrintIps;
} elsif ( "$action" eq "printHosts" ) {
  runPrintHosts;
} elsif ( "$action" eq "printGroups" ) {
  runPrintGroups( $firewall );
} elsif (( "$action" eq "analyseRules" ) or ( "$action" eq "reAnalyseRules" )) {
  # action to print rulebase with analysed matches.
  my $write_secs = (stat "$SIMparam{'SIMtmpDir'}/traffic-analysed-$firewall")[9];
  my $elapsed = (time) - $write_secs;
  if (( $elapsed > 3600 ) or ( $action eq "reAnalyseRules")) {
    analyseTraffic($firewall);
  }
  displayRule("$ruleDir/rule-$firewall","hits");
} elsif ( "$action" eq "printRuleMembers" ) {
  displayRule("$ruleDir/rule-$firewall","members");
} elsif ( "$action" eq "printRules" ) {
  displayRule("$ruleDir/rule-$firewall","detail");
} elsif ( "$action" eq "printServices" ) {
  runPrintServices;
} elsif ( "$action" eq "reportIps" ) {
  runReportIps;
} elsif ( "$action" eq "reportPolicy" ) {
  runReportPolicy;
} else {
  print("<CENTER><HR><TABLE>");
  printMenu("fwan","table", $tool, $action, $firewall);
  print("</TABLE>");
}
print("</TABLE>");
